import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
import { Button, Popup, SelectBox } from 'devextreme-react';
import React, { useCallback, useImperativeHandle, useRef } from 'react';
import { useState } from 'react';
import { intl } from '@/utils';
import { useModel } from 'umi';
import { PaperInitialize } from './service';

const TemplateDialog: React.FC<any> = React.forwardRef((props: any, ref) => {

  const { initialState } = useModel('@@initialState');
  const { zcbfid } = initialState?.curPart as API.CurPart;

  const [visible, setVisible] = useState<boolean>(false);
  const diaParams = useRef<AudDialogShowParams>();
  const refsForm = useRef<any>();
  const [PaperValue, setPaperValue] = useState('')


  const [deletePopupProps, setDeletePopupProps] = useState<{
    visible: boolean;
    onConfirm: () => void;
    onCancel: () => void;
    title: string;
    content: string;
  }>({
    visible: false,
    onConfirm: async () => { },
    onCancel: async () => { },
    title: '',
    content: '',
  });

  // 自定义方法
  useImperativeHandle(ref, () => ({
    show: async (params: AudDialogShowParams) => {
      diaParams.current = params;
      setVisible(true);
    },
    close: () => { setVisible(false) }
  }));

  const onOk = useCallback(() => {
    const res: any = refsForm.current.props?.defaultValue
    const resMbCode: any = refsForm.current.props?.items
    const r: string[] = []
    resMbCode.map((item: any) => {
      if (item.mbmc === PaperValue) r.push(item.mbmc);
    })
    if (res !== r.toString()) {
      setDeletePopupProps({
        visible: true,
        title: intl('pub.prompt', '提示'),
        content: intl('Initialize.the.delContent', '该操作将清除所有的底稿，重新初始化，是否继续？'),
        onConfirm: async () => {
          await PaperInitialize(zcbfid, r.toString());
          if (diaParams.current?.okCallback) {
            diaParams.current?.okCallback('', '');
          }
          setVisible(false);
          setDeletePopupProps({
            visible: false,
            title: '',
            content: '',
            onConfirm: () => { },
            onCancel: () => { }
          })
        },
        onCancel: () => {
          setDeletePopupProps({
            visible: false,
            title: '',
            content: '',
            onConfirm: () => { },
            onCancel: () => { }
          })
        },
      });
    } else {
      setDeletePopupProps({
        visible: true,
        title: intl('prompt', '提示'),
        content: intl('Initialize.the.delContent', '该操作将清除所有的底稿，重新初始化，是否继续？'),
        onConfirm: async () => {
          await PaperInitialize(zcbfid, res);
          if (diaParams.current?.okCallback) {
            diaParams.current?.okCallback('', '');
          }
          setVisible(false);
          setDeletePopupProps({
            visible: false,
            title: '',
            content: '',
            onConfirm: () => { },
            onCancel: () => { }
          });
        },
        onCancel: () => {
          setDeletePopupProps({
            visible: false,
            title: '',
            content: '',
            onConfirm: () => { },
            onCancel: () => { }
          })
        },
      });
    }
  }, [PaperValue])

  const onCancel = useCallback(() => {
    setVisible(false)
  }, [])

  // 获取列表的点击项 
  const onSelectionChangeds = useCallback((e: any) => {
    setPaperValue(e.selectedItem.mbmc);
  }, [PaperValue])

  return (
    <>
      <Popup
        ref={ref}
        visible={visible}
        title={diaParams.current?.args?.title}
        width={500}
        height={200}
        {...props}
        onHiding={() => setVisible(false)}
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.cancel', '取消'),
              onClick: () => onCancel()
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.ok', '确定'),
              type: 'default',
              onClick: () => onOk()
            },
          },
        ]}
        contentRender={() => (
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-around',
              alignItems: 'center'
            }}
          >
            <span>底稿初始化:</span>
            <SelectBox
              width={300}
              ref={refsForm}
              items={diaParams.current?.args?.data}
              displayExpr='mbmc'
              valueExpr='mbmc'
              defaultValue={diaParams.current?.args?.data[0].mbmc}
              searchEnabled={true}
              onSelectionChanged={onSelectionChangeds}
            />
          </div>
        )}
      />
      <ConfirmPopup
        visible={deletePopupProps?.visible}
        onConfirm={deletePopupProps?.onConfirm}
        onCancel={deletePopupProps?.onCancel}
        title={deletePopupProps?.title}
        content={deletePopupProps?.content}
      />
    </>
  );
});


const ConfirmPopup = (props: {
  visible: boolean;
  onConfirm: () => void;
  onCancel: () => void;
  title: string;
  content: string;
}) => {
  return (
    <Popup
      visible={props?.visible}
      title={props?.title}
      onHiding={props?.onCancel}
      width={400}
      height={200}
      showTitle={true}
      showCloseButton={true}
      closeOnOutsideClick={true}
      contentRender={() => {
        return (
          <div>
            <div>{props?.content}</div>
            <div
              style={{
                display: 'flex',
                position: 'absolute',
                bottom: '10px',
                right: '20px',
              }}
            >
              <Button text={intl('pub.cancel', '取消')} onClick={props?.onCancel} />
              <Button
                style={{ marginRight: '10px' }}
                text={intl('pub.ok', '确定')}
                onClick={props?.onConfirm}
                type='default'
              />
            </div>
          </div>
        );
      }}
    />
  );
};

export default TemplateDialog